﻿using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using MySqlConnector;
using SJ.Platform.EFCore.Model;
using SJ.Platform.Extend.IOC.Operation;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.Extend.IOC
{
    /// <summary>
    /// 依赖注入扩展
    /// </summary>
    public static class DependencyExtend
    {
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builder"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection InitDependency(this IServiceCollection services, ContainerBuilder builder, IConfiguration configuration)
        {
            //HTTP 请求的上下文信息
            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().InstancePerLifetimeScope();//.SingleInstance();

            #region 注册服务
            Type baseType = typeof(IDependency);//自定义的空接口
            //动态运行项目的类库
            var compilationLibrary = DependencyContext.Default
                .RuntimeLibraries
                .Where(x => !x.Serviceable
                && x.Name == "SJ.Platform.Extend")
                .ToList();
            var count1 = compilationLibrary.Count;
            List<Assembly> assemblyList = new List<Assembly>();

            foreach (var _compilation in compilationLibrary)
            {
                try
                {
                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
                }
                catch (Exception ex)
                {

                }
            }
            //注册程序集的方式添加依赖
            builder.RegisterAssemblyTypes(assemblyList.ToArray())
             .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)//过滤非抽象类，继承了IDependency接口的类
             .AsImplementedInterfaces()
             .InstancePerLifetimeScope();//实例的生命周期
            #endregion

            #region 注册数据库
            //mysql数据库
            builder.Register(c =>
            {
                var optionsBuilder = new DbContextOptionsBuilder<SJDBContext>();
                optionsBuilder.UseMySql(configuration.GetConnectionString("MySqlConnection"), new MySqlServerVersion(new Version(6, 0, 31))); 
                return new SJDBContext(optionsBuilder.Options);
            }).AsSelf().InstancePerLifetimeScope();

            //mongo数据库
            builder.Register(c =>
            {
                var client = new MongoClient(configuration.GetConnectionString("MongoConnection"));
                return client.GetDatabase(configuration.GetConnectionString("MongoDataBase"));
            }).As<IMongoDatabase>().InstancePerLifetimeScope();
            #endregion

            return services;
        }
    }
}
